package samples.javabean;

import java.awt.Color;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.swing.JFrame;
import javax.swing.JScrollPane;

import org.jgraph.JGraph;
import org.jgraph.graph.DefaultCellViewFactory;
import org.jgraph.graph.DefaultGraphCell;
import org.jgraph.graph.DefaultGraphModel;
import org.jgraph.graph.DefaultPort;
import org.jgraph.graph.GraphConstants;
import org.jgraph.graph.GraphLayoutCache;
import org.jgraph.graph.GraphModel;

public class Graphic {
	
	String webroot;
	String filename; 
	String random;
	
	public Graphic(){
		/*将Webroot指向合适的路径*/
		webroot = "I:\\SourceCode\\workspace\\chapter7\\.deployables\\chapter7";
		filename = "number.png";
	}

	public String getFilename() {
		return filename;
	}
	public void setFilename(String filename) {
		this.filename = filename;
	}
	public String getRandom() {
		return random;
	}
	public void setRandom(String random) {
		this.random = random;
	}

	public void paint(){
		GraphModel model = new DefaultGraphModel();								//设置显示模式
		GraphLayoutCache view = new GraphLayoutCache(model,  				   //创建默认视图
				new	DefaultCellViewFactory());
	 
		JGraph graph = new JGraph(model, view);                					//创建默认视图
		DefaultGraphCell cell = new DefaultGraphCell(random);  					//添加一个Cell，讲random字符串显示
				GraphConstants.setBounds(cell.getAttributes(), new
				Rectangle2D.Double(0,0,100,40));
				GraphConstants.setGradientColor(
				cell.getAttributes(),
				Color.orange);
				GraphConstants.setOpaque(cell.getAttributes(), true);
				DefaultPort port = new DefaultPort();
				cell.add(port);													//插入一个port
				
				graph.getGraphLayoutCache().insert(cell);						//插入这个Cell

					JFrame frame = new JFrame();									//在一个框架中显示Graphic，													
					frame.getContentPane().add(new JScrollPane(graph));				//为了输出到文件
					frame.pack();
					frame.setVisible(false);
									
					try {
					File f = new File(webroot , filename);  						//新建一个文件引用
					ImageOutputStream ios = ImageIO.createImageOutputStream(f);   	//得到一个输出流
					BufferedImage img = graph.getImage(graph.getBackground(), 1);	//得到图像对象。
					ImageIO.write(img,"png",ios);									//写到流里面
					ios.flush();													//刷新流
					ios.close();													//关闭流
						} catch (IOException e) {									//意外处理
						e.printStackTrace();
					} 			
	}
	
}
